//配置路由的地方
import Vue from "vue";
import VueRouter from 'vue-router'
//引入store
import store from "@/store";
//使用插件
import { mapState, mapActions, mapMutations, mapGetters } from 'vuex'
Vue.use(VueRouter)

import routes from './routes'

//先把VueRouter原型对象的push,先保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;

//重写push|replace方法，解决NavigationDuplicated的警告错误
//第一个参数：告诉原来push方法，你往哪里跳转（传递哪些参数）
//第二个参数：成功回调
//第三个参数：失败的回调 
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        //cal1||apply区别
        //相同点，都可以调用函数一次，都可以篡改函数的上下文一次
        //不同点：cal1与apply传递参数：cal1传递参数用逗号隔开，apply方法执行，传递数组
        originPush.call(this, location, resolve, reject)//直接调用会让originPush上下文指向window，所以用call方法篡改上下文为VueRouter
    } else {
        originPush.call(this, location, () => { }, () => { })
    }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        originReplace.call(this, location, resolve, reject)
    } else {
        originReplace.call(this, location, () => { }, () => { })
    }
}


//配置路由
let router = new VueRouter({
    routes: routes,
    //新路由滚动最顶部
    scrollBehavior(to, from, savedPosition) {
        return { x: 0, y: 0 }
    }
})

//全局守卫：前置守卫（在路由跳转之间进行判断）
router.beforeEach(async (to, from, next) => {
    // to要去的页面 from从哪里来 next放行 
    //登录了才有token
    let token = store.state.user.token
    //用户信息
    let name = store.state.user.userinfo.name;
    //用户已经登录
    if (token) {
        //用户登录了不能去login路由,停留在首页
        if (to.path == '/login') {
            next('/home')
        } else {
            //如果用户名有
            if (name) {
                next()
            }
            //没有就派发
            else {
                try {
                    await store.dispatch('user/getUserInfo');
                    next()
                } catch (error) {
                    //token失效了
                    //清除所有用户信息，返回登录页面
                    await store.dispatch('user/userLogout')
                    next('/login')
                }
            }
        }
    }
    //用户未登录 不能去交易相关的地方,个人中心
    else {
        let toPath = to.path
        if (toPath == '/trade' || toPath == '/pay' || toPath == '/paysuccess' || toPath == '/center' || toPath == '/center/myorder') {
            //把未登录想去的地方而没有去的地方，存储在地址栏
            next('/login?redirect=' + toPath)
        } else {
            next()
        }
    }
})



export default router;